/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.swirrel.installer;

import java.awt.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import org.swirrel.annotation.UndoableEditHappened;
import org.swirrel.listener.SwirrelUndoableEditListener;
import org.swirrel.util.MethodCall;

/**
 *
 * @author Gronau
 */
public class UndoableEditListenerInstaller extends AbstractListenerInstaller implements SwirrelListenerInstaller {

    public UndoableEditListenerInstaller() {
        super(Arrays.<Class<? extends Annotation>>asList(UndoableEditHappened.class),
                Arrays.<Class<?>>asList(JTextComponent.class));
    }

    public boolean isListenerAlreadySet(Object obj) {
       Document doc = ((JTextComponent) obj).getDocument();
        if (doc instanceof AbstractDocument) {
            AbstractDocument ad = (AbstractDocument) doc;
            for (UndoableEditListener uel : ad.getUndoableEditListeners()) {
                if (uel instanceof SwirrelUndoableEditListener) {
                    return true;
                }
            }
        }
        return false;
    }

    public void registerListener(Field field, Component comp, List<MethodCall> methodCalls) throws IllegalAccessException {
        Object obj = field.get(comp);
        ((JTextComponent) obj).getDocument().addUndoableEditListener(
                new SwirrelUndoableEditListener(methodCalls.get(0)));
    }
}
